<template>
	<view class="order-out-box">
		<!--  v-if="$accessCheck($Access.orderQuerySearch)" -->
		<view class="header-search-box">
			<view class="search-input-wrapper">
				<u-icon name="search" size="40" color="#879BBA"></u-icon>
				<input 
					type="text" 
					v-model="search_data.keyword" 
					placeholder="请输入搜索内容" 
					placeholder-style="color: #879BBA;"
					@confirm="searchConfirm()"
				/>
				<u-icon 
					v-if="search_data.keyword" 
					name="close" 
					size="32" 
					color="#879BBA"
					@click="search_data.keyword='';searchConfirm()"
				></u-icon>
			</view>
			<view class="filter-btn" @click="openSearch">
				<u-icon name="list" size="44" color="#FB5904"></u-icon>
			</view>
		</view>
		
		<view class="tabs-container">
			<u-tabs
				:list="status_list"
				:current="status_current"
				@change="statusChange"
				inactive-color="#62738E"
				active-color="#FB5904"
				bar-width="32"
				font-size="24"
				gutter="28"
			></u-tabs>
		</view>
		
		<view class="total-count">
			<text>共{{ total }}条订单信息</text>
		</view>
		
		<scroll-view
			scroll-y
			class="order_ul"
			@refresherrefresh="refresherrefresh"
			:refresher-enabled="true"
			:refresher-triggered="refresher_triggered"
			@scrolltolower="scrollTolower"
			:scroll-top="scrollTop"
		>
			<view class="order-card" v-for="(item, index) in order_list" :key="index" @click="goPage(`/pages/order/orderInfo?userCenterId=${item.userCenterId}&id=${item.id}`)">
				<view class="order-header">
					<view class="order-status">
						<view class="status-badge" :class="[getOrderStatusClass(item.orderMsg)]">
							{{ item.orderMsg }}
						</view>
						<text class="order-number">{{ item.no }}</text>
					</view>
					<view class="payment-status">
						<view v-if="parseInt(item.payStatus) === 5" class="payment-badge payment-paid">已支付</view>
						<view v-else-if="parseInt(item.payStatus) === 4" class="payment-badge payment-unpaid">未支付</view>
						<view v-else class="payment-badge payment-partial">部分支付</view>
					</view>
				</view>
				
				<view class="order-content">
					<view class="info-item">
						<view class="info-label">客户名称</view>
						<view class="info-value">{{ item.customerName }}</view>
					</view>
					
					<view class="info-item">
						<view class="info-label">下单时间</view>
						<view class="info-value">{{ $u.timeFormat(item.createTime, 'yyyy-mm-dd hh:MM:ss') }}</view>
					</view>
					
					<view class="info-item">
						<view class="info-label">支付方式</view>
						<view class="info-value">{{ item.payTypeMsg }}</view>
					</view>
					
					<view class="order-amount" :class="[parseInt(item.payStatus) === 5 ? 'paid' : parseInt(item.payStatus) === 4 ? 'unpaid' : 'partial-paid']">
						<view class="amount-label">订单金额</view>
						<view class="amount-value">¥ {{ $utils.formattedNumber(item.payAmount) }}</view>
					</view>
					
					<view class="order-actions">
						<view class="return-status" v-if="parseInt(item.returnStatus) !== 0">
							<u-tag 
								:text="parseInt(item.returnStatus) === 1 ? '部分退货' : '全部退货'" 
								:type="parseInt(item.returnStatus) === 1 ? 'warning' : 'primary'"
								size="mini"
							></u-tag>
						</view>
						<view class="copy-btn">
							<u-button size="mini" type="primary" @click.stop="copyOrderInfo(item.userCenterId, item.id)">复制信息</u-button>
						</view>
					</view>
				</view>
			</view>
			
			<u-loadmore v-if="order_list.length" :status="load_status" />
			<view v-if="!order_list.length" class="empty-view"><u-empty text="暂无订单信息" mode="order"></u-empty></view>
		</scroll-view>
		
		<u-popup v-model="search_show" mode="right">
			<view class="search-pop">
				<uniStatusBar></uniStatusBar>
				<view class="popup-header">
					<text class="popup-title">筛选条件</text>
					<u-icon name="close" size="32" color="#333" @click="search_show = false"></u-icon>
				</view>
				
				<view class="form-view">
					<u-form label-width="160rpx" label-position="left">
						<u-form-item label-position="top" label="下单日期">
							<view class="date-range">
								<picker mode="date" @change="bindDateStartChange">
									<view class="date-picker">
										<text>{{ search_data.start ? $u.timeFormat(search_data.start, 'yyyy-mm-dd') : '开始日期' }}</text>
										<u-icon name="calendar" size="28" color="#879BBA"></u-icon>
									</view>
								</picker>
								<text class="date-separator">至</text>
								<picker mode="date" @change="bindDateEndChange">
									<view class="date-picker">
										<text>{{ search_data.end ? $u.timeFormat(search_data.end, 'yyyy-mm-dd') : '结束日期' }}</text>
										<u-icon name="calendar" size="28" color="#879BBA"></u-icon>
									</view>
								</picker>
							</view>
						</u-form-item>
						
						<u-form-item label="下单客户">
							<view class="form-select" @click="goPage('/pagesT/customer/selCustomer')">
								<text class="select-text">{{ search_data.customerId ? search_data.customerName : '请选择客户' }}</text>
								<u-icon :name="!search_data.customerId ? 'arrow-right' : 'close-circle-fill'" size="28" color="#999999" @click.stop="clearValue('customerId')"></u-icon>
							</view>
						</u-form-item>
						
						<u-form-item label="所属店铺">
							<view class="form-select" @click="goPage('/pagesT/shop/selShop')">
								<text class="select-text">{{ search_data.shopId ? search_data.shopName : '请选择店铺' }}</text>
								<u-icon :name="!search_data.shopId ? 'arrow-right' : 'close-circle-fill'" size="28" color="#999999" @click.stop="clearValue('shopId')"></u-icon>
							</view>
						</u-form-item>
						
						<u-form-item label="支付方式">
							<view class="form-select" @click="goPage('/pagesT/payment/selPayment')">
								<text class="select-text">{{ search_data.payType ? search_data.payTypeName : '请选择支付方式' }}</text>
								<u-icon :name="!search_data.payType ? 'arrow-right' : 'close-circle-fill'" size="28" color="#999999" @click.stop="clearValue('payType')"></u-icon>
							</view>
						</u-form-item>
						
						<u-form-item label="客户类型">
							<view class="form-select" @click="goPage('/pagesT/customer/selCustomerType')">
								<text class="select-text">{{ search_data.customerType ? search_data.customerTypeName : '请选择客户类型' }}</text>
								<u-icon :name="!search_data.customerType ? 'arrow-right' : 'close-circle-fill'" size="28" color="#999999" @click.stop="clearValue('customerType')"></u-icon>
							</view>
						</u-form-item>
						
						<u-form-item label="订单来源">
							<view class="form-select" @click="openFrom('from_show')">
								<text class="select-text">{{ search_data.source ? search_data.sourceName : '请选择订单来源' }}</text>
								<u-icon :name="!search_data.source ? 'arrow-right' : 'close-circle-fill'" size="28" color="#999999" @click.stop="clearValue('source')"></u-icon>
							</view>
						</u-form-item>
					</u-form>
				</view>

				<view class="search-btn">
					<view class="reset-btn" @click="clearValue()">重置</view>
					<view class="confirm-btn" @click="searchConfirm">确定</view>
				</view>
			</view>
		</u-popup>
		
		<addBtn v-if="$accessCheck($Access.OrderAddAddOrder)" url="/pages/order/OrderAdd"></addBtn>
		<u-select @confirm="fromChange" v-model="from_show" :list="order_from"></u-select>
		<u-action-sheet @click="selKeyType" :list="keywordType_list" v-model="show_key_menu"></u-action-sheet>
	</view>
</template>

<script>
import uniStatusBar from '../../components/uni-status-bar.vue';
export default {
	components: {
		uniStatusBar
	},
	props: {
		customerData: {
			type: [Object, String],
			default: ''
		},
		shopData: {
			type: [Object, String],
			default: ''
		},
		paymentData: {
			type: [Object, String],
			default: ''
		},
		customerTypeData: {
			type: [Object, String],
			default: ''
		}
	},
	data() {
		return {
			refresher_triggered: false,
			from_show: false,
			search_show: false,
			pay_type_list: [],
			pay_index: 0,
			load_status: 'nomore',
			page: 1,
			pageSize: 10,
			total: 0,
			status_current: 0,
			order_state: 'all',
			order_list: [],
			keywordType: '单据编号',
			show_key_menu: false,
			search_data: {
				keywordType: '',
				keyword: '',
				payType: '',
				payTypeName: '',
				start: '',
				end: '',
				customerId: '',
				customerName: '',
				customerType: '',
				customerTypeName: '',
				source: '',
				sourceName: '',
				shopId: '',
				shopName: ''
			},
			order_from: [
				{
					label: 'ios',
					value: 1
				},

				{
					label: '安卓',
					value: 2
				},
				{
					label: '微信小程序',
					value: 3
				},
				{
					label: '后台创建',
					value: 4
				},
				{
					label: 'H5页面',
					value: 5
				},
				{
					label: 'pc页面',
					value: 6
				},
				{
					label: '字节跳动小程序',
					value: 8
				}
			],
			status_list: [
				{
					value: 'all',
					name: '全部'
				},
				{
					value: 'waitAudit',
					name: '待审核'
				},
				{
					value: 'waitOutStock',
					name: '待出库'
				},
				{
					value: 'hasOutStock',
					name: '已出库'
				},
				{
					value: 'finish',
					name: '已完成'
				},
				{
					value: 'close',
					name: '已关闭'
				}
			],
			scrollTop: -1,
			keywordType_list: [
				{
					text: '单据编号',
					value: 1
				},
				{
					text: '自提码',
					value: 2
				},
				{
					text: '商品名称',
					value: 3
				},
				{
					text: '商品编码',
					value: 4
				},
				{
					text: '收货人',
					value: 5
				},
				{
					text: '电话',
					value: 6
				},
				{
					text: '业务员',
					value: 7
				},
				{
					text: '详细地址',
					value: 8
				}
			]
		};
	},
	watch: {
		customerData(val) {
			if (val) {
				this.search_data.customerName = val.name;
				this.search_data.customerId = val.id;
			}
		},
		shopData(val) {
			if (val) {
				this.search_data.shopName = val.name;
				this.search_data.shopId = val.id;
			}
		},
		paymentData(val) {
			if (val) {
				this.search_data.payTypeName = val.title;
				this.search_data.payType = val.id;
			}
		},
		customerTypeData(val) {
			if (val) {
				this.search_data.customerTypeName = val.name;
				this.search_data.customerType = val.id;
			}
		}
	},
	created() {
		this.getAllOrder();
	},
	methods: {
		getOrderStatusClass(status) {
			const statusMap = {
				'待审核': 'status-auditing',
				'已关闭': 'status-closed',
				'已出库': 'status-shipped',
				'已完成': 'status-completed',
				'待出库': 'status-pending-shipment',
				'待取消': 'status-pending-cancel'
			};
			return statusMap[status] || 'status-default';
		},
		copyOrderInfo(userCenterId, orderId) {
			this.$u.api
				.getOrderInfoById(userCenterId, {
					orderId: orderId
				})
				.then(res => {
					const data = res.data;
					const goodsList = data.goodsData.map(item => {
						return `- ${item.goodsName} (数量: ${Number(item.outNum) || Number(item.buyNum)})`;
					});
					const goodsString = goodsList.join('\n');
					const copyInfo = `【订单信息】
客户: ${data.customerName}
电话: ${data.customerMobile}
业务员: ${data.salesManName || '无'}
商品列表:
${goodsString}
备注: ${data.remark || '无'}`;
					uni.setClipboardData({
						data: copyInfo,
						success: () => {
							this.$u.toast('订单信息已复制');
						}
					});
				}).catch(err => {
					this.$u.toast('复制失败，请稍后重试');
					console.error('复制订单信息失败:', err);
				});
		},
		openFrom(key) {
			console.log(13);
			this[key] = true;
		},
		selKeyType(index) {
			this.keywordType = this.keywordType_list[index].text;
			this.search_data.keywordType = this.keywordType_list[index].value;
		},
		fromChange(e) {
			this.search_data.source = e[0].value;
			this.search_data.sourceName = e[0].label;
		},
		scrollTolower() {
			if (this.total / this.pageSize > this.page) {
				this.page += 1;
				this.getData();
			}
		},
		openSearch() {
			this.search_show = true;
		},
		statusChange(index) {
			this.scrollTop = 0;
			this.$nextTick(() => {
				this.scrollTop = -1;
			});
			this.status_current = index;
			this.order_state = this.status_list[index].value;
			this.searchConfirm();
		},
		clearValue(params) {
			if (!params) {
				this.search_data = {
					keyword: '',
					payType: '',
					payTypeName: '',
					start: '',
					end: '',
					customerId: '',
					customerName: '',
					customerType: '',
					customerTypeName: '',
					source: '',
					sourceName: '',
					shopId: '',
					shopName: ''
				};
				this.searchConfirm();
			} else {
				this.search_data[params] = '';
			}
		},
		searchConfirm() {
			this.search_show = false;
			this.page = 1;
			this.getData();
		},
		getData() {
			const obj = {
				keyword: this.search_data.keyword,
				payType: this.search_data.payType,
				shopId: this.search_data.shopId,
				startTime: this.search_data.start,
				endTime: this.search_data.end,
				customerId: this.search_data.customerId,
				customerType: this.search_data.customerType,
				source: this.search_data.source
			};
			const isKey = this.$utils.isSerch(obj);
			if (isKey) {
				this.searchOrder(obj);
			} else {
				this.getAllOrder();
			}
		},
		getAllOrder() {
			this.load_status = 'loading';
			let params = {
				page: this.page,
				pageSize: this.pageSize,
				state: this.order_state
			};
			this.$u.api
				.getAllOrder(params)
				.then(res => {
					this.refresher_triggered = false;
					if (this.page === 1) {
						this.order_list = res.data;
					} else {
						this.order_list = this.order_list.concat(res.data);
					}
					this.order_list = this.order_list.map(item => {
						return {
							...item,
							goods_list: item.goods_list || []
						};
					});
					this.total = res.pageTotal;
					this.load_status = this.$utils.loadStatus(this.page, this.pageSize, this.total);
				})
				.catch(err => {
					this.refresher_triggered = false;
				});
		},
		searchOrder(obj) {
			this.load_status = 'loading';
			let params = {
				page: this.page,
				pageSize: this.pageSize,
				state: this.order_state,
				keywordType: this.search_data.keywordType,
				...obj
			};
			this.$u.api
				.keywordSearch(params)
				.then(res => {
					this.refresher_triggered = false;
					if (this.page === 1) {
						this.order_list = res.data;
					} else {
						this.order_list = this.order_list.concat(res.data);
					}
					this.order_list = this.order_list.map(item => {
						return {
							...item,
							goods_list: item.goods_list || []
						};
					});
					this.total = res.pageTotal;
					this.load_status = this.$utils.loadStatus(this.page, this.pageSize, this.total);
				})
				.catch(err => {
					this.refresher_triggered = false;
				});
		},
		bindDateStartChange(e) {
			this.search_data.start = this.$utils.timeByTimestamp(e.detail.value + ' 00:00:00');
		},
		bindDateEndChange(e) {
			this.search_data.end = this.$utils.timeByTimestamp(e.detail.value + ' 23:59:59');
		},
		refresherrefresh() {
			this.refresher_triggered = true;
			this.page = 1;
			this.getData();
		}
	}
};
</script>

<style scoped lang="scss">
.order-out-box {
	background-color: #f5f7fa;
	min-height: 100vh;
}

.header-search-box {
	background-color: #ffffff;
	padding: 24rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	
	.search-input-wrapper {
		flex: 1;
		height: 72rpx;
		background-color: #f5f7fa;
		border-radius: 36rpx;
		display: flex;
		align-items: center;
		padding: 0 24rpx;
		margin-right: 20rpx;
		
		input {
			flex: 1;
			height: 72rpx;
			font-size: 28rpx;
			margin: 0 16rpx;
		}
	}
	
	.filter-btn {
		width: 72rpx;
		height: 72rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 50%;
		background-color: rgba(251, 89, 4, 0.1);
	}
}

.tabs-container {
	background-color: #ffffff;
	padding: 10rpx 0;
	margin-top: 20rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.total-count {
	padding: 20rpx 30rpx;
	font-size: 24rpx;
	color: #879bba;
}

.order_ul {
	height: calc(90vh - 240rpx);
	// padding: 0 20rpx;
}

.order-card {
	background-color: #ffffff;
	border-radius: 12rpx;
	margin-bottom: 24rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	overflow: hidden;
	
	.order-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 24rpx;
		border-bottom: 2rpx solid #f5f7fa;
		
		.order-status {
			display: flex;
			align-items: center;
			
			.order-number {
				font-size: 28rpx;
				font-weight: 500;
				color: #2d405e;
				margin-left: 16rpx;
				font-family: DIN-Medium;
			}
		}
		
		.payment-icon {
			width: 102rpx;
			height: 29rpx;
		}
	}
	
	.order-content {
		padding: 24rpx;
		
		.info-item {
			display: flex;
			justify-content: space-between;
			margin-bottom: 20rpx;
			
			.info-label {
				font-size: 26rpx;
				color: #879bba;
				width: 160rpx;
			}
			
			.info-value {
				flex: 1;
				font-size: 26rpx;
				color: #2d405e;
				text-align: right;
				font-weight: 500;
			}
		}
		
		.order-amount {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx;
			border-radius: 8rpx;
			margin: 20rpx 0;
			
			.amount-label {
				font-size: 28rpx;
				font-weight: 500;
				color: #2d405e;
			}
			
			.amount-value {
				font-size: 32rpx;
				font-weight: bold;
				font-family: DIN-Medium;
			}
		}
		
		.paid {
			background-color: rgba(0, 195, 149, 0.1);
			.amount-value {
				color: #00c395;
			}
		}
		
		.unpaid {
			background-color: rgba(246, 119, 120, 0.1);
			.amount-value {
				color: #f67778;
			}
		}
		
		.partial-paid {
			background-color: rgba(251, 89, 4, 0.1);
			.amount-value {
				color: #FB5904;
			}
		}
		
		.order-actions {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-top: 20rpx;
		}
	}
}

.status-badge {
	padding: 8rpx 16rpx;
	border-radius: 8rpx;
	font-size: 24rpx;
	color: #fff;
	text-align: center;
	font-weight: 500;
}
.status-auditing { background-color: #ff9900; } /* orange */
.status-closed { background-color: #909399; } /* grey */
.status-shipped { background-color: #19be6b; } /* green */
.status-completed { background-color: #2979ff; } /* blue */
.status-pending-shipment { background-color: #fa3534; } /* red */
.status-pending-cancel { background-color: #f29100; } /* dark orange */
.status-default { background-color: #606266; } /* dark grey */

.payment-badge {
	padding: 4rpx 12rpx;
	border-radius: 6rpx;
	font-size: 22rpx;
	color: #fff;
	font-weight: 500;
}
.payment-paid { background-color: #00c395; }
.payment-unpaid { background-color: #f67778; }
.payment-partial { background-color: #FB5904; }

.search-pop {
	width: 600rpx;
	height: 100vh;
	background-color: #ffffff;
	
	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 80rpx 30rpx 30rpx;
		border-bottom: 2rpx solid #f5f7fa;
		
		.popup-title {
			font-size: 32rpx;
			font-weight: bold;
			color: #2d405e;
		}
	}
	
	.form-view {
		padding: 30rpx;
		
		.date-range {
			display: flex;
			align-items: center;
			
			.date-picker {
				flex: 1;
				height: 72rpx;
				background-color: #f5f7fa;
				border-radius: 8rpx;
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 0 20rpx;
				font-size: 24rpx;
				color: #2d405e;
			}
			
			.date-separator {
				margin: 0 20rpx;
				color: #879bba;
			}
		}
		
		.form-select {
			display: flex;
			justify-content: space-between;
			align-items: center;
			height: 72rpx;
			background-color: #f5f7fa;
			border-radius: 8rpx;
			padding: 0 20rpx;
			
			.select-text {
				font-size: 26rpx;
				color: #2d405e;
			}
		}
	}
	
	.search-btn {
		position: absolute;
		bottom: 40rpx;
		left: 0rpx;
		right: 30rpx;
		display: flex;
		
		.reset-btn, .confirm-btn {
			flex: 1;
			height: 80rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			border-radius: 40rpx;
			font-size: 28rpx;
		}
		
		.reset-btn {
			background-color: #f5f7fa;
			color: #879bba;
			margin-right: 20rpx;
		}
		
		.confirm-btn {
			background-color: #FB5904;
			color: #ffffff;
		}
	}
}

.empty-view {
	padding-top: 200rpx;
}
</style>
